package com.miracle.main.module.mvp.presenter;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.support.annotation.MainThread;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.miracle.basemvp.base.BasePresenter;
import com.miracle.basemvp.base.BaseResponse;
import com.miracle.basemvp.base.IPresenter;
import com.miracle.basemvp.lifecycle.rx.RxDefaultObserver;
import com.miracle.basemvp.util.CommonDialogUtils;
import com.miracle.basemvp.util.Utils;
import com.miracle.common.CommonConfig;
import com.miracle.common.bean.User.User;
import com.miracle.common.state.user.LoginContext;
import com.miracle.common.state.user.LoginState;
import com.miracle.common.util.PreferencesUtils;
import com.miracle.common.util.S;
import com.miracle.main.module.mvp.contract.FileContract;
import com.miracle.main.util.FileUploadObserver;
import com.miracle.main.util.MultipartBuilder;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import javax.inject.Inject;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * com.miracle.main.module.mvp.presenter
 * (c)2018 AIR Times Inc. All rights reserved.
 *
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/7/10 15:20
 * @see com.miracle.main.module.mvp.presenter
 */
public class FilePresenter extends BasePresenter<FileContract.View, FileContract.Model>
        implements IPresenter {

    @Inject
    public FilePresenter(FileContract.View view, FileContract.Model model) {
        super(view, model);
    }

    public void uploadFiles(LifecycleProvider<ActivityEvent> lifecycleProvider, List<String> list) {
        final String url = CommonConfig.BASE_URL + "upload";
        final List<File> files = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            File file = new File(list.get(i));
            files.add(file);
        }
        final CommonDialogUtils commonDialogUtils = new CommonDialogUtils((Activity) mView);
        commonDialogUtils.showProgress();
        final FileUploadObserver fileUploadObserver = new FileUploadObserver<ResponseBody>() {
            @Override
            public void onUploadSuccess(ResponseBody o) {
                commonDialogUtils.dismissProgress();
                BaseResponse response = format(((Activity) mView), o);
                if (response.isSuccessed()) {
                    mView.uploadSucc();
                    Toast.makeText((Activity) mView, "onUploadSuccess", Toast
                            .LENGTH_SHORT).show();
                }
            }

            @Override
            public void onUploadFail(Throwable e) {
                commonDialogUtils.dismissProgress();
            }

            @Override
            public void onProgress(int progress) {
                Toast.makeText((Activity) mView, "onProgress: "+progress, Toast
                        .LENGTH_SHORT).show();
            }
        };
        //HACK
        //FIXME
        final String session = PreferencesUtils.getPreferences(((Activity) mView), PreferencesUtils
                .State.USER_SESSIONID);

        io.reactivex.Observable.just("")
                .subscribeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<ResponseBody>>() {
                    @Override
                    public ObservableSource<ResponseBody> apply(String s) throws Exception {
                        final MultipartBody body = MultipartBuilder.filesToMultipartBody(files,
                                fileUploadObserver, session);
                        return mModel.uploadFiles(url, body, session);
                    }
                }).compose(lifecycleProvider.<ResponseBody>bindUntilEvent
                (ActivityEvent.DESTROY))
                .subscribe(fileUploadObserver);

//        mModel.uploadFiles(url, body, session)
//                .compose(lifecycleProvider.<ResponseBody>bindUntilEvent
//                        (ActivityEvent.DESTROY))
//                .subscribe(fileUploadObserver);
    }

    public BaseResponse format(Context context, ResponseBody responseBody) {
        BaseResponse response = null;
        try {
            if (responseBody != null) {
                long contentLength = responseBody.contentLength();
                BufferedSource source = responseBody.source();
                source.request(Integer.MAX_VALUE);
                Buffer buffer = source.buffer();
                if (contentLength != 0) {
                    Gson gson = Utils.obtainAppComponentFromContext(context).gson();
                    response = gson.fromJson(buffer.clone().readString(Charset.forName("UTF-8")),
                            BaseResponse.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

}
